<template>
  <base-modal
    :show.sync="visible"
    :title="$t('common.base.copy')"
    class="edit-plan-name-modal"
    width="500px"
  >
    <el-form
      ref="form"
      class="form-container"
      :rules="rules"
      label-position="top"
      :model="form"
    >
      <el-form-item :label="$t('task.edit.planName')" prop="planName">
        <el-input v-model="form.planName" :placeholder="t('common.placeholder.inputSomething', {data1: t('task.edit.planName')})"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { openAccurateTab } from '@src/util/platform'
import { checkPlanName } from '@src/modules/smartPlan/api/index.js'
import { t } from '@src/locales'
import _ from 'lodash'
export default {
  name: 'copy-plan-name-dialog',
  props: {
    formValue: {
      type: Object,
      default: () => ({})
    },
    planId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      pending: false,
      form: {
        planName: ''
      },
      rules: {
        planName: [
          { required: true, message: t('common.placeholder.inputSomething', {data1: t('task.edit.planName')}), trigger: 'blur' },
          { max: 50, message: t('common.validate.nameLimit', {limit: 50}), trigger: 'blur' },
          { validator: this.checkName, trigger: ['blur', 'change'] },
        ]
      }
    }
  },
  methods: {
    open(planName) {
      this.visible = true
      this.form.planName = planName
    },
    submit() {
      this.$refs.form.validate().then(valid => {
        if (valid) {
          // 缓存数据，跳转编辑智能计划页面
          localStorage.setItem('createSmartPlanData', JSON.stringify({
            planName: this.form.planName,
            planType: this.formValue.planType,
            planTypeId: this.formValue.planTypeId,
            planTypeName: this.formValue.planTypeName,
          }))
          let fromId = window.frameElement?.getAttribute('id');
          openAccurateTab({
            type: PageRoutesTypeEnum.PageSmartPlanCopy,
            params: `planId=${this.planId}`,
            fromId
          })
          this.visible = false
        }
      })
    },
    checkName: _.debounce(function(rule, value, callback) {
      if (!value) return callback()
      checkPlanName({planName: value}).then(result => {
        if (!result.succ) {
          callback(new Error(result.message))
        } 
        callback()
      })
    }, 1000),
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 24px;
}
</style>